function loadFromLocalStorage() {
    return JSON.parse(localStorage.myTodolist);
}

function storeToLocalStorage(items) {
    localStorage.myTodolist = JSON.stringify(items);
}

function addItem(list, value) {

    var item = document.createElement("li");
    
    item.innerHTML = '<input type="checkbox" />' + 
                     '<span class="item">' + value + '</span>'; 

    list.appendChild(item);
}

function reloadTodoItems(items) {
    
    var list = document.querySelector("#todolist ul");

    for (var i = 0, len = items.length; i < len; i++) {
        addItem(list, items[i]);
    }
}

window.onload = function() {

    // bind keydonw event for input
    var input = document.querySelector("#todolist input"),
        list = document.querySelector("#todolist ul"),
        selectBtn = document.querySelector("#select"),
        deleteBtn = document.querySelector("#delete"),
        items;

    if (typeof localStorage.myTodolist === 'undefined') {
        storeToLocalStorage(new Array());
    } else {
        reloadTodoItems(loadFromLocalStorage());
    }

    input.addEventListener("keydown", function(event) {
        
        if (event.keyCode == "13" && input.value.length > 0) {
            addItem(list, input.value);
            items = loadFromLocalStorage();
            items.push(input.value);
            storeToLocalStorage(items);
            input.value = "";
        }
    });

    selectBtn.addEventListener("click", function(event) {
        
        var inputs = document.querySelectorAll("#todolist input");

        for (var i = 0, len = inputs.length; i < len; i++) {
            if (inputs[i].type === "checkbox") {
                inputs[i].checked = true;
            }
        }
    });

    deleteBtn.addEventListener("click", function(event) {

        var inputs = document.querySelectorAll("#todolist input"),
            list = document.querySelector("#todolist ul"),
            items = loadFromLocalStorage();

        for (var i = 1, len = inputs.length; i < len; i++) {
            if (inputs[i].checked) {
                list.removeChild(inputs[i].parentElement);
                // something wrong
                items.splice(i-1, 1);
            }
        }

        storeToLocalStorage(items);
    });

};